package handler

import (
	"developer-branch/api/request"
	"developer-branch/glodal"
	"developer-branch/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func RoomCreate(c *gin.Context) {
	var req request.RoomCreate
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	room := model.Room{
		MakeRoomUserId: c.GetUint("userId"),
		RoomName:       req.RoomName,
	}
	glodal.DB.Create(&room)
	if room.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "建群失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "建群成功",
		"data": room,
	})
}

func RoomUserAdd(c *gin.Context) {
	var req request.RoomUserAdd
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	err = glodal.DB.Where("id = ?", req.RoomUserId).Find(&user).Error
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该用户不存在，无法拉入群中",
			"data": nil,
		})
		return
	}
	var roomoneuser model.RoomUser
	err = glodal.DB.Where("room_user_id = ?", req.RoomUserId).Find(&roomoneuser).Error
	if roomoneuser.RoomUserId == req.RoomUserId {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该用户已在群内",
			"data": nil,
		})
		return
	}
	roomuser := model.RoomUser{
		RoomUserId: req.RoomUserId,
		UserType:   req.UserType,
		RoomId:     req.RoomId,
	}
	err = glodal.DB.Create(&roomuser).Error
	if roomuser.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "群拉人失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "群拉人成功",
		"data": roomuser,
	})
}
